package handler

import (
	"admin-nexus-backend/internal/dto"
	"admin-nexus-backend/internal/model"
	"admin-nexus-backend/internal/service"
	"admin-nexus-backend/pkg/response"
	"fmt"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// DataPermissionHandler 数据权限处理器
type DataPermissionHandler struct {
	roleService *service.RoleService
}

// NewDataPermissionHandler 创建数据权限处理器
func NewDataPermissionHandler(roleService *service.RoleService) *DataPermissionHandler {
	return &DataPermissionHandler{
		roleService: roleService,
	}
}

// GetDataPermissionList 获取数据权限列表
// @Summary 获取数据权限列表
// @Description 获取所有角色的数据权限配置
// @Tags 数据权限管理
// @Accept json
// @Produce json
// @Param roleId query uint false "角色ID"
// @Success 200 {object} response.Response{data=[]dto.DataPermissionResponse}
// @Router /api/v1/data-permissions [get]
func (h *DataPermissionHandler) GetDataPermissionList(c *gin.Context) {
	var query dto.DataPermissionQueryParams
	if err := c.ShouldBindQuery(&query); err != nil {
		response.BadRequest(c, "参数错误")
		return
	}

	// 获取所有角色
	roles, err := h.roleService.GetRoleList(&dto.RoleQueryParams{
		Page:     1,
		PageSize: 1000, // 获取所有角色
	})
	if err != nil {
		response.InternalServerError(c, "获取角色列表失败")
		return
	}

	var result []dto.DataPermissionResponse
	roleList, ok := roles.List.([]model.Role)
	if !ok {
		response.InternalServerError(c, "角色列表数据格式错误")
		return
	}

	for _, role := range roleList {
		// 如果指定了roleId，只返回该角色的数据权限
		if query.RoleID != nil && role.ID != *query.RoleID {
			continue
		}

		// 获取角色的数据权限
		dataPermission, err := h.roleService.GetRoleDataPermission(role.ID)
		if err != nil {
			continue
		}

		// 解析组织ID列表
		var orgIDs []uint
		if dataPermission.OrgIDs != "" {
			for _, idStr := range strings.Split(dataPermission.OrgIDs, ",") {
				if id, err := strconv.ParseUint(idStr, 10, 64); err == nil {
					orgIDs = append(orgIDs, uint(id))
				}
			}
		}

		result = append(result, dto.DataPermissionResponse{
			RoleID:    role.ID,
			RoleName:  role.Name,
			DataScope: dataPermission.DataScope,
			OrgIDs:    orgIDs,
			CreatedAt: dataPermission.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt: dataPermission.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	response.SuccessWithData(c, result)
}

// GetDataPermissionByRoleID 根据角色ID获取数据权限
// @Summary 根据角色ID获取数据权限
// @Description 获取指定角色的数据权限配置
// @Tags 数据权限管理
// @Accept json
// @Produce json
// @Param roleId path uint true "角色ID"
// @Success 200 {object} response.Response{data=dto.DataPermissionResponse}
// @Router /api/v1/data-permissions/{roleId} [get]
func (h *DataPermissionHandler) GetDataPermissionByRoleID(c *gin.Context) {
	roleIDStr := c.Param("roleId")
	roleID, err := strconv.ParseUint(roleIDStr, 10, 64)
	if err != nil {
		response.BadRequest(c, "角色ID格式错误")
		return
	}

	// 获取角色信息
	role, err := h.roleService.GetRoleByID(uint(roleID))
	if err != nil {
		response.NotFound(c, "角色不存在")
		return
	}

	// 获取数据权限
	dataPermission, err := h.roleService.GetRoleDataPermission(uint(roleID))
	if err != nil {
		response.InternalServerError(c, "获取数据权限失败")
		return
	}

	// 解析组织ID列表
	var orgIDs []uint
	if dataPermission.OrgIDs != "" {
		for _, idStr := range strings.Split(dataPermission.OrgIDs, ",") {
			if id, err := strconv.ParseUint(idStr, 10, 64); err == nil {
				orgIDs = append(orgIDs, uint(id))
			}
		}
	}

	result := dto.DataPermissionResponse{
		RoleID:    role.ID,
		RoleName:  role.Name,
		DataScope: dataPermission.DataScope,
		OrgIDs:    orgIDs,
		CreatedAt: dataPermission.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt: dataPermission.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	response.SuccessWithData(c, result)
}

// UpdateDataPermission 更新数据权限
// @Summary 更新数据权限
// @Description 更新指定角色的数据权限配置
// @Tags 数据权限管理
// @Accept json
// @Produce json
// @Param roleId path uint true "角色ID"
// @Param body body dto.UpdateDataPermissionRequest true "数据权限信息"
// @Success 200 {object} response.Response
// @Router /api/v1/data-permissions/{roleId} [put]
func (h *DataPermissionHandler) UpdateDataPermission(c *gin.Context) {
	roleIDStr := c.Param("roleId")
	roleID, err := strconv.ParseUint(roleIDStr, 10, 64)
	if err != nil {
		response.BadRequest(c, "角色ID格式错误")
		return
	}

	var req dto.UpdateDataPermissionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "参数错误: "+err.Error())
		return
	}

	// 验证数据权限范围
	if req.DataScope < 1 || req.DataScope > 5 {
		response.BadRequest(c, "数据权限范围必须在1-5之间")
		return
	}

	// 如果是自定义数据范围，必须提供组织ID列表
	if req.DataScope == 5 && len(req.OrgIDs) == 0 {
		response.BadRequest(c, "自定义数据范围时必须提供组织ID列表")
		return
	}

	// 构建组织ID字符串
	var orgIDsStr string
	if req.DataScope == 5 {
		var orgIDStrs []string
		for _, id := range req.OrgIDs {
			orgIDStrs = append(orgIDStrs, fmt.Sprintf("%d", id))
		}
		orgIDsStr = strings.Join(orgIDStrs, ",")
	}

	// 更新数据权限
	dataPermission := &model.RoleDataPermission{
		RoleID:    uint(roleID),
		DataScope: req.DataScope,
		OrgIDs:    orgIDsStr,
	}

	if err := h.roleService.UpdateRoleDataPermission(uint(roleID), dataPermission); err != nil {
		response.InternalServerError(c, "更新数据权限失败: "+err.Error())
		return
	}

	response.Success(c)
}

// DeleteDataPermission 删除数据权限（重置为默认）
// @Summary 删除数据权限
// @Description 删除指定角色的数据权限配置（重置为默认全部数据权限）
// @Tags 数据权限管理
// @Accept json
// @Produce json
// @Param roleId path uint true "角色ID"
// @Success 200 {object} response.Response
// @Router /api/v1/data-permissions/{roleId} [delete]
func (h *DataPermissionHandler) DeleteDataPermission(c *gin.Context) {
	roleIDStr := c.Param("roleId")
	roleID, err := strconv.ParseUint(roleIDStr, 10, 64)
	if err != nil {
		response.BadRequest(c, "角色ID格式错误")
		return
	}

	// 重置为默认数据权限（全部数据）
	dataPermission := &model.RoleDataPermission{
		RoleID:    uint(roleID),
		DataScope: 1, // 全部数据
		OrgIDs:    "",
	}

	if err := h.roleService.UpdateRoleDataPermission(uint(roleID), dataPermission); err != nil {
		response.InternalServerError(c, "删除数据权限失败: "+err.Error())
		return
	}

	response.Success(c)
}

// BatchUpdateDataPermissions 批量更新数据权限
// @Summary 批量更新数据权限
// @Description 批量更新多个角色的数据权限配置
// @Tags 数据权限管理
// @Accept json
// @Produce json
// @Param body body map[uint]dto.UpdateDataPermissionRequest true "角色ID到数据权限的映射"
// @Success 200 {object} response.Response
// @Router /api/v1/data-permissions/batch [put]
func (h *DataPermissionHandler) BatchUpdateDataPermissions(c *gin.Context) {
	var req map[string]dto.UpdateDataPermissionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "参数错误: "+err.Error())
		return
	}

	// 批量更新
	for roleIDStr, permReq := range req {
		roleID, err := strconv.ParseUint(roleIDStr, 10, 64)
		if err != nil {
			continue
		}

		// 构建组织ID字符串
		var orgIDsStr string
		if permReq.DataScope == 5 {
			var orgIDStrs []string
			for _, id := range permReq.OrgIDs {
				orgIDStrs = append(orgIDStrs, fmt.Sprintf("%d", id))
			}
			orgIDsStr = strings.Join(orgIDStrs, ",")
		}

		dataPermission := &model.RoleDataPermission{
			RoleID:    uint(roleID),
			DataScope: permReq.DataScope,
			OrgIDs:    orgIDsStr,
		}

		if err := h.roleService.UpdateRoleDataPermission(uint(roleID), dataPermission); err != nil {
			continue
		}
	}

	response.Success(c)
}
